package com.gujh.security.authentication.jwt;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.gujh.security.exception.JwtAuthenticationException;

public class HutoolJwtValidator implements JwtValidator {

    @Override
    public String validate(String token) {
        // 验签
        boolean verify = JWTUtil.verify(token, "key".getBytes());
        if (!verify) {
            throw new JwtAuthenticationException("非法令牌");
        }
        // 过期
        final JWT jwt = JWTUtil.parseToken(token);
        NumberWithFormat expireTime = (NumberWithFormat) jwt.getPayload("expire_time");
        if (System.currentTimeMillis() > expireTime.longValue()) {
            throw new JwtAuthenticationException("令牌已失效");
        }
        // 返回
        return (String) jwt.getPayload("username");
    }
}

